﻿using ErrorOr;
using Gym.Application.Common.Interfaces;
using Gym.Application.Profiles.Common;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gym.Application.Profiles.Queries.ListProfiles
{
    public class ListProfilesQueryHandle : IRequestHandler<ListProfilesQuery, ErrorOr<List<Profile?>>>
    {
        private readonly ITrainersRepository _trainersRepository;
        private readonly IParticipantsRepository _participantsRepository;
        private readonly IAdminsRepository _adminsRepository;

        public ListProfilesQueryHandle(ITrainersRepository trainersRepository, IParticipantsRepository participantsRepository, IAdminsRepository adminsRepository)
        {
            _trainersRepository = trainersRepository;
            _participantsRepository = participantsRepository;
            _adminsRepository = adminsRepository;
        }

        public async Task<ErrorOr<List<Profile?>>> Handle(ListProfilesQuery request, CancellationToken cancellationToken)
        {
            var trainerProfile = await _trainersRepository.GetProfileByUserIdAsync(request.UserId);
            var participantProfile = await _participantsRepository.GetProfileByUserIdAsync(request.UserId);
            var adminProfile = await _adminsRepository.GetProfileByUserIdAsync(request.UserId);

            var profiles = new[] { trainerProfile, participantProfile, adminProfile}
            .Where(profile => profile != null)
            .ToList();          

            if (profiles.Count == 0)
            {
                return Error.NotFound(description:"没有找到用户信息");
            }

            return profiles;
        }
    }
}
